/* eslint-disable no-mixed-operators */
/* eslint-disable no-restricted-globals */
/* eslint-disable no-param-reassign */
/* eslint-disable no-plusplus */
import Base from 'base'; // eslint-disable-line
import debounce from 'lodash.debounce';
import Model from './model';
import template from './tpl/ui.tpl';
import imageSelectorTpl from './tpl/imageSelector.tpl';
import exportedDataTpl from './tpl/exportedData.tpl';
import imagesTpl from './tpl/images.tpl';
// import Drawing from './lib/drawing';
import {
  rotateRectanglePoints,
  calculateSlope,
  findDuplicatePointsValue,
  getRandomColor,
  trianglesIntersect,
  findMaxYPriorityPoint,
} from "./utils/calus";

export default Base.View.extend({
  initialize($el, data) {
    this.addClass("./resources/css/main.css");
    this.model = new Model({
      materials: data.materials,
      preset: data.preset,
      recordStrokes: data.recordStrokes,
      isEditMode: false,
      defaultMode: data.defaultMode,
      defaultDrawMode: data.defaultDrawMode,
      defaultLineDash: data.defaultLineDash,
      defaultStrokeColor: data.defaultStrokeColor,
      defaultStrokeWidth: data.defaultStrokeWidth,
      snapImage: data.snapImage,
      widgetWidth: $el.width(),
      widgetHeight: $el.height(),
      fullPath: data.fullPath,
      recordStrokeLeft: data.recordStrokeLeft,
      recordStrokeTop: data.recordStrokeTop,
    });

    this.debouncedAddImageMovement = debounce(
      () => this.model.addImageMovement(),
      500
    );
    this.open = true;
    this.render();

    if (!this.model.get("isEditMode")) {
      this.setMode(this.model.get("defaultMode"));
    }
    window.MyWidget = this;
    console.log(this);
    if (this.useExtension) {
      this.useExtension("statisticsViewer", {
        __statisticsRenderSrc: "pendulumTriangle/statisticsViewer.js",
      });
    }
  },

  __supportInteract: true,

  events: {

    'click .preset-tools button[data-tool="move"]': "enterMoveMode",
    'click .preset-tools button[data-tool="add-image"]': "showImageSelector",
    'click .preset-tools button[data-tool="settings"]': "enterSettingsMode",
    'click .preset-tools button[data-tool="set-transform-origin"]':
      "enterSetTransformOriginMode",
    'click .preset-tools button[data-tool="remove"]': "enterRemoveMode",

    "click .image-selector .image-container": "selectImage",
    "click .modal .ok": "hideModal",
    "click .workspace .image-container": "onClickImage",
    "mousedown .workspace .image-container ": "onMousedownImage",
    "touchstart .workspace .image-container ": "onMousedownImage",
    "mousedown .workspace .image-container .rotate-btn":
      "onMousedownImageRotateBtn",
    "touchstart .workspace .image-container .rotate-btn":
      "onMousedownImageRotateBtn",
    "mousedown .workspace .image-container .resizer": "onMousedownImageResizer",
    "touchstart .workspace .image-container .resizer":
      "onMousedownImageResizer",
    "mousedown .workspace .transform-origin": "onMousedownTransformOrigin",
    "touchstart .workspace .transform-origin": "onMousedownTransformOrigin",
    "mousemove .workspace": "onMousemoveWorkspace",
    "touchmove .workspace": "onMousemoveWorkspace",
    "touchend .workspace": "onMouseupWorkspace",
    "mouseup .workspace": "onMouseupWorkspace",
    "touchleave .workspace": "onMouseupWorkspace",
    "mouseleave .workspace": "onMouseupWorkspace",
    "change .image-props input": "onImagePropChange",
  },

  reset() {
    this.model.initData();
    this.renderImages();
    this.$workspace.find("#drawing-canvas").css("pointer-events", "none");
    let canvas = this.$workspace.find("#drawing-canvas")[0];
    let ctx = canvas.getContext("2d");
    ctx.clearRect(0, 0, canvas.width, canvas.height);
   
  },
  submit() {
    const result = {
      answer: this.model.get("answer"),
      allOperations: this.model.get("allOperations"),
      drawing: this.model.get("drawing"),
    };
    console.log(JSON.stringify(result));
    const blob = new Blob([JSON.stringify(result)], {
      type: "application/json",
    });
    const file = new File([blob], "data.json", { type: "application/json" });
    if (typeof this.uploadWidgetFile === "function")
      this.uploadWidgetFile(file);
  },

  /**
   * 切换显示/隐藏
   */
  toggleDisplay() {
    if (this.$el.css("display") === "none") {
      this.show();
    } else {
      this.hide();
    }
  },

  setRecordStrokePosition(e) {
    const clientX =
      e.type === "touchstart" || e.type === "touchmove"
        ? e.originalEvent.touches[0].clientX
        : e.clientX;
    const clientY =
      e.type === "touchstart" || e.type === "touchmove"
        ? e.originalEvent.touches[0].clientY
        : e.clientY;
    let recordStroke = this.$el.find(".recordStroke")[0];
    recordStroke.style.display = "block";
    const widgetRect = this.$el[0].getBoundingClientRect();
    recordStroke.style.left = clientX - widgetRect.left - 15 + "px";
    recordStroke.style.top = clientY - widgetRect.top - 15 + "px";
    this.model.set("recordStrokeLeft", clientX - widgetRect.left - 15);
    this.model.set("recordStrokeTop", clientY - widgetRect.top - 15);
  },

  onClickImage(e) {
    if (this.open) {
      const editMode = this.model.get("editMode");
      const imageIndex = parseInt(e.currentTarget.dataset.index, 10);
      console.log("onClickImage", editMode, imageIndex);
      if (editMode === "settings") {
        this.showImageProps(imageIndex);
      } else if (editMode === "remove") {
        this.model.removeImage(imageIndex);
        this.renderImages();
      } else if (editMode === "set-transform-origin") {
        this.showImageTransformOriginIndicator(imageIndex);
      }
    }
  },

  onImagePropChange(e) {
    const imageIndex = parseInt(
      this.$el.find(".modal .image-props")[0].dataset.index,
      10
    );
    const propName = e.currentTarget.parentElement.dataset.prop;
    const imageData = this.model.getElementData("image", imageIndex);
    if (!imageData || !propName) return;
    if (propName === "width" || propName === "height") {
      imageData[propName] = parseInt(e.currentTarget.value, 10);
      const $imageElement = this.$workspace.find(
        `.image-container[data-index="${imageIndex}"]`
      );
      $imageElement.css(propName, `${imageData[propName]}px`);
    } else if (
      [
        "draggable",
        "infiniteDrag",
        "rotatable",
        "rotateBtnVisible",
        "hidden",
      ].indexOf(propName) !== -1
    ) {
      imageData[propName] = e.currentTarget.checked;
    } else if (propName === "rotateStep") {
      imageData[propName] = parseInt(e.currentTarget.value, 10);
    } else if (propName === "group") {
      imageData[propName] = `${e.currentTarget.value}`;
    }
  },



  onMousedownTransformOrigin(e) {
    e.stopPropagation(); // 防止触发拖动
    const clientX =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientX : e.clientX;
    const clientY =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientY : e.clientY;
    const widgetRect = this.$el[0].getBoundingClientRect();
    this.mousePos = [clientX - widgetRect.left, clientY - widgetRect.top];
    this.isDraggingTransformOrigin = true;
    this.$transformOriginIndicator = this.$workspace.find(".transform-origin");
  },

  onMousedownImageRotateBtn(e) {

    e.stopPropagation(); // 防止触发拖动
    const clientX =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientX : e.clientX;
    const clientY =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientY : e.clientY;
    const widgetRect = this.$el[0].getBoundingClientRect();
    this.mousePos = [clientX - widgetRect.left, clientY - widgetRect.top];
    this.rotatingImageContainer = e.currentTarget.parentElement;
    // 旋转可能有旋转角度步长，需要将缓存当前角度直到旋转了接近一个步长时才真正旋转
    this.imageRotationCache = 0;
  },
  onMousedownImageResizer(e) {
    const clientX =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientX : e.clientX;
    const clientY =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientY : e.clientY;
    this.mousedownStartX = clientX;
    this.mousedownStartY = clientY;
    e.stopPropagation(); // 防止触发拖动
    this.isMousedownImageResizer = true;
  },

  onMousedownImage(e) {
    e.preventDefault();
    e.stopPropagation();
    if (this.open) {
      const clientX =
        e.type === "touchstart" ? e.originalEvent.touches[0].clientX : e.clientX;
      const clientY =
        e.type === "touchstart" ? e.originalEvent.touches[0].clientY : e.clientY;
      if (this.model.get("isEditMode")) {
        this.mousedownElement = e.currentTarget;
        const widgetRect = this.$el[0].getBoundingClientRect();
        this.mousePos = [clientX - widgetRect.left, clientY - widgetRect.top];
      } else if (this.model.get("mode") === "move") {
        console.log(111);
        const imageContainer = e.currentTarget;
        const imageIndex = parseInt(e.currentTarget.dataset.index, 10);
        const imageData = this.model.get("images")[imageIndex];
        this.imageIndex = imageIndex;
        if (imageData && imageData.draggable) {
          const widgetRect = this.$el[0].getBoundingClientRect();
          this.mousePos = [clientX - widgetRect.left, clientY - widgetRect.top];
          if (imageData.infiniteDrag) {
            // 无限拖动选项，拖动时复制一个选项
            console.log(22222);
            const wrapperElem = document.createElement("div");
            wrapperElem.innerHTML = imageContainer.outerHTML;
            const clonedElem = wrapperElem.children[0];
            const clonedData = JSON.parse(JSON.stringify(imageData));
            clonedData.infiniteDrag = false;
            clonedData.hidden = false;
            this.model.get("images").push(clonedData);
            clonedElem.dataset.index = this.model.get("images").length - 1;
            imageContainer.parentElement.appendChild(clonedElem);
            this.mousedownElement = clonedElem;
          } else {
            this.mousedownElement = imageContainer;
          }
          this.mousedownTime = Date.now(); // 记录拖动开始的时间，拖动开始 500ms 以内不吸附，否则被吸附的不好拖开
          this.allImagesRects = this.model.getImageRects(); // 获取所有边框顶点坐标以计算可吸附的顶点
          this.allImagesRects.splice(imageIndex, 1); // 去掉自己的边框

          if (this.model.get("recordStrokes")) {
            this.setRecordStrokePosition(e);
            this.model.addImageMovement();
          }
        }
      }
    }
  },
  onMousemoveWorkspace(e) {
    if (this.isDraggingTransformOrigin) {
      const clientX =
        e.type === "touchmove" ? e.originalEvent.touches[0].clientX : e.clientX;
      const clientY =
        e.type === "touchmove" ? e.originalEvent.touches[0].clientY : e.clientY;
      const widgetRect = this.$el[0].getBoundingClientRect();
      const pos = [clientX - widgetRect.left, clientY - widgetRect.top];
      const imageIndex = parseInt(
        this.$transformOriginIndicator[0].dataset.index,
        10
      );
      const imageData = this.model.getElementData("image", imageIndex);
      const deltaPos = [pos[0] - this.mousePos[0], pos[1] - this.mousePos[1]];
      const originX = (imageData.originX * imageData.width) / 100 + deltaPos[0];
      const originY =
        (imageData.originY * imageData.height) / 100 + deltaPos[1];
      imageData.originX = (originX * 100) / imageData.width;
      imageData.originY = (originY * 100) / imageData.height;
      const indicatorSize = { width: 20, height: 20 };
      this.$transformOriginIndicator
        .css("top", `${imageData.top + originY - indicatorSize.height / 2}px`)
        .css("left", `${imageData.left + originX - indicatorSize.width / 2}px`);
      this.$workspace
        .find(`.images > .image-container[data-index="${imageIndex}"]`)
        .css("transform-origin", `${imageData.originX}% ${imageData.originY}%`);
      this.mousePos = pos;
    } else if (this.rotatingImageContainer) {
      const clientX =
        e.type === "touchmove" ? e.originalEvent.touches[0].clientX : e.clientX;
      const clientY =
        e.type === "touchmove" ? e.originalEvent.touches[0].clientY : e.clientY;
      const widgetRect = this.$el[0].getBoundingClientRect();
      const pos = [clientX - widgetRect.left, clientY - widgetRect.top];
      const imageIndex = parseInt(
        this.rotatingImageContainer.dataset.index,
        10
      );
      const imageData = this.model.getElementData("image", imageIndex);
      const center = [
        imageData.left + (imageData.originX * imageData.width) / 100,
        imageData.top + (imageData.originY * imageData.height) / 100,
      ];
      const v1 = [this.mousePos[0] - center[0], this.mousePos[1] - center[1]];
      const v2 = [pos[0] - center[0], pos[1] - center[1]];
      const angle =
        (Math.atan2(
          (v1[0] * v2[1] - v2[0] * v1[1]) / (v1[0] * v2[0] + v1[1] * v2[1]),
          1
        ) *
          180) /
        Math.PI;
      if (!imageData.rotation) imageData.rotation = 0;
      let realAngle = angle;
      if (imageData.rotateStep) {
        this.imageRotationCache += angle;
        realAngle =
          this.imageRotationCache -
          (this.imageRotationCache % imageData.rotateStep);
        this.imageRotationCache %= imageData.rotateStep;
      }
      imageData.rotation += realAngle;
      this.rotatingImageContainer.style.transform = `rotate(${imageData.rotation}deg)`;
      this.mousePos = pos;
    } else if (this.mousedownElement) {
      const clientX =
        e.type === "touchmove" ? e.originalEvent.touches[0].clientX : e.clientX;
      const clientY =
        e.type === "touchmove" ? e.originalEvent.touches[0].clientY : e.clientY;
      const widgetRect = this.$el[0].getBoundingClientRect();
      const pos = [clientX - widgetRect.left, clientY - widgetRect.top];
      const deltaPos = [pos[0] - this.mousePos[0], pos[1] - this.mousePos[1]];
      this.mousePos = pos;
      const elemType = this.mousedownElement.dataset.type;
      const elemIndex = parseInt(this.mousedownElement.dataset.index, 10);
      const elemData = this.model.getElementData(elemType, elemIndex);
      if (!elemData) return;
      elemData.left += deltaPos[0];
      elemData.top += deltaPos[1];
      const deltaTime = Date.now() - this.mousedownTime;
      if (deltaTime > 500) {
        // 拖动开始500ms以后再有吸附功能
        const [stickOriginDx, stickOriginDy] =
          this.stickImageToOriginalPosition(elemData);
        if (stickOriginDx !== 0 || stickOriginDy !== 0) {
          elemData.left += stickOriginDx;
          elemData.top += stickOriginDy;
        } else if (this.model.get("snapImage")) {
          const [stickDx, stickDy] = this.stickImage(elemData, elemIndex);
          elemData.left += stickDx;
          elemData.top += stickDy;
        }
      }
      this.mousedownElement.style.top = `${elemData.top}px`;
      this.mousedownElement.style.left = `${elemData.left}px`;
      if (this.model.get("recordStrokes")) {
        this.setRecordStrokePosition(e);
      }
    } else if (this.isMousedownImageResizer) {
      this.setImgResizer(e);
    }
  },

  setImgResizer(e) {
    const clientX =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientX : e.clientX;
    const clientY =
      e.type === "touchstart" ? e.originalEvent.touches[0].clientY : e.clientY;
    let clientXDistance = clientX - this.mousedownStartX;
    let clientYDistance = clientY - this.mousedownStartY;
    const imageData = this.model.get("images")[this.imageIndex];
    if (imageData && imageData.isResizer) {
      const $imageContainer = this.$workspace.find(
        `.image-container[data-index="${this.imageIndex}"]`
      );
      let proportion = imageData.width / imageData.height;
      let newWidth =
        parseFloat($imageContainer[0].style.width) + clientXDistance;
      if (imageData.equalProportion) {
        $imageContainer[0].style.width = newWidth + "px";
        $imageContainer[0].style.height = newWidth / proportion + "px";
      } else {
        let newHeight =
          parseFloat($imageContainer[0].style.height) + clientYDistance;
        $imageContainer[0].style.width = newWidth + "px";
        $imageContainer[0].style.height = newHeight + "px";
      }
      this.mousedownStartX = clientX;
      this.mousedownStartY = clientY;
    }
  },

  onMouseupWorkspace() {
    if (
      !this.model.get("isEditMode") &&
      (this.mousedownElement || this.rotatingImageContainer)
    ) {
      this.debouncedAddImageMovement(); // avoid duplicated call addImageMovement
    }
    this.mousedownElement = null;
    this.rotatingImageContainer = null;
    this.isDraggingTransformOrigin = false;
    this.isMousedownImageResizer = false;
  },

  // 移动图片时顶点吸附，返回移动量
  stickImage(imageData) {
    if (!this.allImagesRects) return [0, 0];
    const imageRect = this.model.getImageRect(imageData);
    const threshold = 64; // 距离的平方
    let distance = Infinity; // 当前最小值
    let srcPoint = null;
    let targetPoint = null;
    this.allImagesRects.forEach((rect) => {
      rect.forEach((point) => {
        imageRect.forEach((selfPoint) => {
          const d2 =
            (point[0] - selfPoint[0]) ** 2 + (point[1] - selfPoint[1]) ** 2;
          if (d2 <= threshold && d2 < distance) {
            srcPoint = selfPoint;
            targetPoint = point;
            distance = d2;
          }
        });
      });
    });
    if (srcPoint && targetPoint) {
      return [targetPoint[0] - srcPoint[0], targetPoint[1] - srcPoint[1]];
    }
    return [0, 0];
  },

  // 吸附图片到初始位置
  stickImageToOriginalPosition(imageData) {
    const imageIndex = this.model.get("images").indexOf(imageData);
    const initialImageData = this.model.get("initialImages")[imageIndex];
    if (!initialImageData) return [0, 0];
    if (typeof imageData.rotation === "number") {
      const originalRotation = initialImageData.rotation || 0;
      const deltaRotation = Math.abs(imageData.rotation - originalRotation);
      // 旋转过不吸附
      if (deltaRotation > 1) return [0, 0];
    }
    const threshold = 64; // 距离的平方
    const imageRect = this.model.getImageRect(imageData);
    const initialImageRect = this.model.getImageRect(initialImageData);
    const center = [
      (imageRect[0][0] + imageRect[2][0]) / 2,
      (imageRect[0][1] + imageRect[2][1]) / 2,
    ];
    const initialCenter = [
      (initialImageRect[0][0] + initialImageRect[2][0]) / 2,
      (initialImageRect[0][1] + initialImageRect[2][1]) / 2,
    ];
    const distance =
      (center[0] - initialCenter[0]) ** 2 + (center[1] - initialCenter[1]) ** 2;
    if (distance < threshold) {
      return [initialCenter[0] - center[0], initialCenter[1] - center[1]];
    }
    return [0, 0];
  },

  enterSettingsMode() {
    this.$el.find(".preset-tools button").removeClass("active");
    this.$el
      .find('.preset-tools button[data-tool="settings"]')
      .addClass("active");
    this.$workspace.find(".transform-origin").hide();
    this.model.set("editMode", "settings");
  },
  enterRemoveMode() {
    this.$el.find(".preset-tools button").removeClass("active");
    this.$el
      .find('.preset-tools button[data-tool="remove"]')
      .addClass("active");
    this.$workspace.find(".transform-origin").hide();
    this.model.set("editMode", "remove");
  },
  enterMoveMode() {
    this.$el.find(".preset-tools button").removeClass("active");
    this.$el.find('.preset-tools button[data-tool="move"]').addClass("active");
    this.$workspace.find(".transform-origin").hide();
    this.model.set("editMode", "move");
  },
  enterSetTransformOriginMode() {
    this.$el.find(".preset-tools button").removeClass("active");
    this.$el
      .find('.preset-tools button[data-tool="set-transform-origin"]')
      .addClass("active");
    this.model.set("editMode", "set-transform-origin");
  },

  showImageTransformOriginIndicator(imageIndex) {
    const imgData = this.model.get("images")[imageIndex];
    const $transformOriginIndicator = this.$workspace.find(".transform-origin");
    const indicatorSize = { width: 20, height: 20 };
    let transformOriginX =
      typeof imgData.originX === "number" ? imgData.originX : 50; // 百分比
    let transformOriginY =
      typeof imgData.originY === "number" ? imgData.originY : 50; // 百分比
    transformOriginX = (transformOriginX * imgData.width) / 100;
    transformOriginY = (transformOriginY * imgData.height) / 100;
    $transformOriginIndicator[0].dataset.index = imageIndex;
    $transformOriginIndicator
      .css(
        "top",
        `${imgData.top + transformOriginY - indicatorSize.height / 2}px`
      )
      .css(
        "left",
        `${imgData.left + transformOriginX - indicatorSize.width / 2}px`
      )
      .css("display", "block");
  },

  selectImage(e) {
    this.$imageSelector.find(".image-container").removeClass("selected");
    e.currentTarget.className += " selected";
  },

  hideModal() {
    const editMode = this.model.get("editMode");
    if (editMode === "selectImage") {
      const $selectedImage = this.$el.find(
        ".modal .image-selector .image-container.selected"
      );
      if ($selectedImage.length !== 0) {
        const index = parseInt($selectedImage[0].dataset.index, 10);
        this.model.addImage(index);
        this.renderImages();
      }
    }
    this.$el.find(".modal").hide();
  },

  showImageSelector() {
    const $modal = this.$el.find(".modal");
    $modal.find(".body").hide();
    $modal.find(".image-selector-container").show();
    $modal.show();
    this.$el.find(".preset-tools button").removeClass("active");
    this.model.set("editMode", "selectImage");
  },
  showImageProps(imageIndex) {
    const $modal = this.$el.find(".modal");
    $modal.find(".body").hide();
    const $imageProps = $modal.find(".image-props");
    $imageProps[0].dataset.index = imageIndex;
    const imageData = this.model.getElementData("image", imageIndex);
    $imageProps.find('[data-prop="width"] input').val(imageData.width);
    $imageProps.find('[data-prop="height"] input').val(imageData.height);
    $imageProps.find('[data-prop="draggable"] input')[0].checked =
      imageData.draggable;
    $imageProps.find('[data-prop="infiniteDrag"] input')[0].checked =
      imageData.infiniteDrag;
    $imageProps.find('[data-prop="rotatable"] input')[0].checked =
      imageData.rotatable;
    $imageProps.find('[data-prop="rotateBtnVisible"] input')[0].checked =
      imageData.rotateBtnVisible;
    $imageProps
      .find('[data-prop="rotateStep"] input')
      .val(imageData.rotateStep || 0);
    $imageProps.find('[data-prop="group"] input').val(imageData.group || "");
    $imageProps.find('[data-prop="hidden"] input')[0].checked =
      !!imageData.hidden;
    $imageProps.show();
    $modal.show();
  },

  renderImages() {
    this.$workspace.find(".images").html(imagesTpl(this.model.toJSON()));
  },

  render() {
    this.$el.html(template(this.model.toJSON()));
    this.$workspace = this.$el.find(".workspace");
    this.renderImages();
    if (this.model.get("isEditMode")) {
      this.$imageSelector = this.$el.find(".modal .image-selector");
      this.$imageSelector.html(imageSelectorTpl(this.model.toJSON()));
    }
  },


  // // 交互接口，设置模式：移动图片模式、绘画模式
  setMode(mode) {
    let mode_;
    if (typeof mode === "string") {
      mode_ = mode.toLowerCase();
    } else if (typeof mode === "object" && typeof mode.value === "string") {
      mode_ = mode.value.toLowerCase();
    }
    if (["move", "draw"].indexOf(mode_) === -1) return;
    this.model.set("mode", mode_);
    if (mode_ === "move") {
      this.$workspace.find("#drawing-canvas").css("pointer-events", "none");
    } else {
      this.$workspace.find("#drawing-canvas").css("pointer-events", "auto");
    }
  },


  // 拼好了
  finished() {
    let images = this.model.get("images");
    images = images.filter(item => item.infiniteDrag == false);
    let trianglesPoint = []  // 存放三角形的各个顶点

    images.forEach(item => {
      let { left, top, width, height, rotation, materialIndex } = item
      trianglesPoint.push(rotateRectanglePoints(top, left, width, height, rotation))
    })
    // overlap angle 是否是叠角 首先是有两个三角形
    let isOvaerLapAngle = false

    if (trianglesPoint.length == 2) {
      isOvaerLapAngle = trianglesIntersect(trianglesPoint)
      console.log("两个三角形相交，相交面积为：" + isOvaerLapAngle);
    }
    this.isOvaerLapAngle = isOvaerLapAngle
    let duplicatePoint = findDuplicatePointsValue(trianglesPoint).filter(item => item[0])

    let circleCenterLocation = [] // 第一次画圆的所有圆心位置
    trianglesPoint.forEach(item => {
      circleCenterLocation.push(...Object.values(item))
    })
    this.model.set("trianglesPoint", trianglesPoint)
    duplicatePoint.forEach(item1 => {
      circleCenterLocation = circleCenterLocation.filter(item2 => {
        return item1[0].join('') != item2.join('')
      })
    })
    duplicatePoint.forEach(item => {
      circleCenterLocation.push(item[0])
    })
    let canvas = this.$workspace.find("#drawing-canvas")[0];
    let ctx = canvas.getContext("2d");
    circleCenterLocation.forEach(item => {
      ctx.beginPath();
      ctx.arc(item[0], item[1], 30, 0, 2 * Math.PI);
      ctx.strokeStyle = 'red';
      ctx.stroke();
      ctx.closePath(); // 关闭路径
    })
    let clickPoint = []
    this.$workspace.find("#drawing-canvas").css("pointer-events", "auto");
    this.tag = true
    canvas.addEventListener("mousedown", (event) => {
      event.stopPropagation();
      event.preventDefault();
      if (this.tag) {
        let rect = canvas.getBoundingClientRect();
        let x = event.clientX - rect.left; // 获取相对于 Canvas 左上角的 x 坐标
        let y = event.clientY - rect.top;
        // 检查点击位置是否在圆的范围内
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        for (let i = 0; i < circleCenterLocation.length; i++) {
          let dx = x - circleCenterLocation[i][0];
          let dy = y - circleCenterLocation[i][1];
          let distance = Math.sqrt(dx * dx + dy * dy); // 计算点击位置到圆心的距离
          // 如果点击位置在圆的范围内，则执行相应操作
          if (distance <= 30) {
            clickPoint = circleCenterLocation[i];
            // 点击的圆的位置是有公共点
            let isCommonPoint = this.isduplicatePoint(duplicatePoint, clickPoint)
            this.model.set("clickPoint", clickPoint)
            this.model.set("isCommonPoint", isCommonPoint)
            this.tag = false
            break; // 如果找到了被点击的圆，就退出循环
          }
        }
        this.markAngle(canvas)
        this.$workspace.find(".rotate-btn").hide();
        // this.$workspace.find("#drawing-canvas").css("pointer-events", "none");
        // this.$workspace.find("img").css("pointer-events", "auto");
        // this.open = false;
      }
    }
    )

  },
  // 交互接口 标记角度
  markAngle(canvas) {
    let ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    this.renderDrawing(canvas)
    let circleLocation = this.model.get("circleLocation")
    console.log("circleLocation", circleLocation);
    circleLocation.forEach((item, index) => {
      const { point, num, isFilled, color } = item
      this.drawCircle(canvas, point[0], point[1], color, num, isFilled)
    })
    let clickAngles = []
    let clickAnglesIndex = []
    canvas.addEventListener("click", (event) => {
      event.stopPropagation();
      event.preventDefault();
      let rect = canvas.getBoundingClientRect();
      let x = event.clientX - rect.left;
      let y = event.clientY - rect.top;
      // 第二次画圆所有的圆心的位置
      for (let i = 0; i < circleLocation.length; i++) {
        let dx = x - circleLocation[i].point[0];
        let dy = y - circleLocation[i].point[1];
        let distance = Math.sqrt(dx * dx + dy * dy);
        if (distance <= 30) {
          if (clickAnglesIndex.indexOf(i) == -1) {
            clickAnglesIndex.push(i);
            clickAngles.push(this.angleDegs[i])
            circleLocation[i].isFilled = true
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            this.renderDrawing(canvas)
            const draw = this.model.get("drawing")
            this.model.set("drawing", { ...draw, circleLocation })
            circleLocation.forEach((item, index) => {
              const { point, num, isFilled, color } = item
              this.drawCircle(canvas, point[0], point[1], color, num, isFilled)
            })
            break
          } else {
            clickAnglesIndex = clickAnglesIndex.filter((item, index) => item != i)
            clickAngles = clickAngles.filter((item, index) => item != this.angleDegs[i])
            circleLocation[i].isFilled = false
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            this.renderDrawing(canvas)
            const draw = this.model.get("drawing")
            this.model.set("drawing", { ...draw, circleLocation })
            circleLocation.forEach((item, index) => {
              const { point, num, isFilled, color } = item
              this.drawCircle(canvas, point[0], point[1], color, num, isFilled)
            })
            break
          }
        }
      }
    
      this.clickAnglesIndex = clickAnglesIndex
      this.clickAngles = clickAngles
    }
    )

  },
  // 生成等式
  generateEquation() {
    let images = this.model.get("images");
    let isCommonPoint = this.model.get("isCommonPoint")
    images = images.filter(item => item.infiniteDrag == false);
    let trianglesPoint = []  // 存放三角形的各个顶点
    images.forEach(item => {
      let { left, top, width, height, rotation } = item
      trianglesPoint.push(rotateRectanglePoints(top, left, width, height, rotation))
    })
    let myAnswer = 0
    let highPoint = findMaxYPriorityPoint(trianglesPoint);
    let clickAngles = this.clickAngles
    let Equation
    if (!isCommonPoint) {
      if (this.clickAnglesIndex[0] == 0) {
        Equation = `${this.angleDegs[0]}°`
        myAnswer = this.angleDegs[0]
      } else {
        Equation = `180° - ${this.angleDegs[0]}° = ${180-this.angleDegs[0]}°`
        myAnswer = 180-this.angleDegs[0]
      }
    } else {
      if (!this.isOvaerLapAngle) {
       if(this.clickAnglesIndex.indexOf(this.angleDegs.length-1) >-1) {
       const tempArr = this.angleDegs.filter((item, index) => this.clickAnglesIndex.indexOf(index)  == -1)
        Equation =`180° - (${tempArr.join('° +')})° = ${180-tempArr.reduce((acc, curr) => acc + curr, 0)}°`
        myAnswer = 180-tempArr.reduce((acc, curr) => acc + curr, 0)
       }else {
        Equation = clickAngles.join('° +') + '° =' + clickAngles.reduce((acc, curr) => acc + curr, 0) + '°';
        myAnswer = clickAngles.reduce((acc, curr) => acc + curr, 0)
       }
      } else {
        console.log("isOvaerLapAngle",isCommonPoint);
        const length = this.clickAnglesIndex.length
        if (length === 1) {
          if (this.clickAnglesIndex.indexOf(0) > -1) {
            Equation = `${this.angleDegs[0]}° - ${this.angleDegs[1]}° =  ${this.angleDegs[0] - this.angleDegs[1]}° `;
            myAnswer = this.angleDegs[0] - this.angleDegs[1]
          } else {
            Equation = `180° - ${this.angleDegs[0]}° = ${180 - this.angleDegs[0]}°`
            myAnswer = 180 - this.angleDegs[0]
          }
        } else {
          Equation =  `180° - (${this.angleDegs[0]}° - ${this.angleDegs[1]})  = ${180 - (this.angleDegs[0] - this.angleDegs[1])}°`
          myAnswer =180 - (this.angleDegs[0] - this.angleDegs[1])
        }
      }
    }
    const draw = this.model.get("drawing")
    this.model.set("drawing", { ...draw, generateEquation: { Equation, highPoint } })
    this.model.set("answer", myAnswer)
    let canvas = this.$workspace.find("#drawing-canvas")[0];
    let ctx = canvas.getContext("2d");
    ctx.font = "30px Arial";
    ctx.fillStyle = "red";
    ctx.fillText(
      Equation,
      (highPoint[0] - 40),
      (highPoint[1] + 50)
    );

  },
  calculateAngleBetweenLines(x1, y1, x2, y2, x3, y3, x4, y4) {
    let slope1 = calculateSlope(x1, y1, x2, y2);
    let slope2 = calculateSlope(x3, y3, x4, y4);
    // 处理斜率为正无穷或负无穷的情况
    if (slope1 === Infinity || slope1 === -Infinity) {
      let angleRad = Math.abs(slope2) === Infinity ? 0 : 90 - Math.atan(Math.abs(slope2)) * (180 / Math.PI);
      return this.handleAngle(angleRad);
    }
    if (slope2 === Infinity || slope2 === -Infinity) {
      let angleRad = Math.abs(slope1) === Infinity ? 0 : 90 - Math.atan(Math.abs(slope1)) * (180 / Math.PI);
      return this.handleAngle(angleRad);
    }
    // 计算夹角的弧度值
    let angleRad = Math.abs(Math.atan(Math.abs((slope2 - slope1) / (1 + slope1 * slope2))));
    console.log(angleDeg);
    let angleDeg = angleRad * (180 / Math.PI);
    // 优化后的角度范围判断逻辑
    if (angleDeg >= 25 && angleDeg < 35) {
      return 30;
    } else if (angleDeg >= 40 && angleDeg < 50) {
      return 45;
    } else if (angleDeg >= 55 && angleDeg < 65) {
      return 60;
    } else if (angleDeg >= 85 && angleDeg < 95) {
      return 90;
    }
    // 默认情况下返回计算的弧度值
    return angleRad;
  },
  handleAngle(angleDeg) {
    if (angleDeg > 25 && angleDeg < 35) {
      return 30;
    } else if (angleDeg > 40 && angleDeg < 50) {
      return 45;
    } else if (angleDeg > 55 && angleDeg < 65) {
      return 60;
    } else if (angleDeg > 85 && angleDeg < 95) {
      return 90;
    }
  },
  compareSlopes(slopes, slop) {
    let num = 0;
    for (let i = 0; i < slopes.length; i++) {
      if (slopes[i] == slop || slop > 200) {
        num++;
      }
    }
    // 根据条件返回 true 或 false
    if (num >= 2) {
      return false;
    } else {
      return true;
    }
  },
  renderDrawing(canvas) {
    let clickPoint = this.model.get("clickPoint")
    let isCommonPoint = this.model.get("isCommonPoint")
    let images = this.model.get("images");
    images = images.filter(item => item.infiniteDrag == false);
    let trianglesPoint = []  // 存放三角形的各个顶点
    images.forEach(item => {
      let { left, top, width, height, rotation } = item
      trianglesPoint.push(rotateRectanglePoints(top, left, width, height, rotation))
    })
    this.angleDegs = []  // 所有的角度
    this.slopes = []  // 所有的斜率
    if (!isCommonPoint) {
      let indice = this.findPointAtTriangleIndex(trianglesPoint, clickPoint)
      let filteredData = trianglesPoint.filter((_, index) => index == indice)
      filteredData.forEach(obj => {
        for (const key in obj) {
          if (obj[key].join('') == clickPoint.join('')) {
            delete obj[key];
          }
        }
      })
      let outerAnglePoint = []
      filteredData.forEach(item => {
        for (const key in item) {
          const element = item[key];
          let slope = calculateSlope(clickPoint[0], clickPoint[1], element[0], element[1]);
          slope = parseFloat(slope.toFixed(1))
          let isExtend = this.compareSlopes(this.slopes, slope)
          if (isExtend) {
            // 计算反向延长线的坐标
            let extensionEndX = clickPoint[0] - (element[0] - clickPoint[0]);
            let extensionEndY = clickPoint[1] - (element[1] - clickPoint[1]);
            outerAnglePoint.push([extensionEndX, extensionEndY])
          }
        }
      })
      this.drawLineWithExtension(canvas, filteredData, false)
      this.drawAngleWithNumber(canvas, filteredData, false)
      let outerAnglePoint1 = outerAnglePoint[1]
      let outerAnglePoint2 = Object.values(filteredData[filteredData.length - 1])[0]
      // 绘制外角
      this.drawOuterAngleWithNumber(canvas, outerAnglePoint1, outerAnglePoint2, clickPoint, filteredData.length + 1)
    } else {
      let indices = trianglesPoint.map((obj, index) => {
        if (Object.values(obj).some(arr => arr.includes(clickPoint[0]) && arr.includes(clickPoint[1]))) {
          return index;
        }
      }).filter(index => index !== undefined);
      let filteredData = indices.map(index => trianglesPoint[index]);

      filteredData.forEach(obj => {
        for (const key in obj) {
          if (obj[key].join('') == clickPoint.join('')) {
            delete obj[key];
          }
        }
      })
      filteredData.forEach(item => {
        for (const key in item) {
          const element = item[key];
          let slope = calculateSlope(clickPoint[0], clickPoint[1], element[0], element[1]);
          slope = parseFloat(slope.toFixed(1))
          this.slopes.push(slope)
        }
      })

      let outerAnglePoint = []
      filteredData.forEach(item => {
        for (const key in item) {
          const element = item[key];
          let slope = calculateSlope(clickPoint[0], clickPoint[1], element[0], element[1]);
          slope = parseFloat(slope.toFixed(1))
          let isExtend = this.compareSlopes(this.slopes, slope)
          if (isExtend) {
            // 计算反向延长线的坐标
            let extensionEndX = clickPoint[0] - (element[0] - clickPoint[0]);
            let extensionEndY = clickPoint[1] - (element[1] - clickPoint[1]);
            outerAnglePoint.push([extensionEndX, extensionEndY])
          }
        }
      })
      console.log(" this.isOvaerLapAngle", this.isOvaerLapAngle);
      if (!this.isOvaerLapAngle) {
        this.drawLineWithExtension(canvas, filteredData, this.isOvaerLapAngle)
        this.drawAngleWithNumber(canvas, filteredData, this.isOvaerLapAngle)
        let outerAnglePoint1 = outerAnglePoint[0]
        let outerAnglePoint2 = Object.values(filteredData[filteredData.length - 1])[0]
        this.drawOuterAngleWithNumber(canvas, outerAnglePoint1, outerAnglePoint2, clickPoint, filteredData.length + 1)
      } else {
        console.log(JSON.stringify(filteredData));
        this.drawLineWithExtension(canvas, filteredData, this.isOvaerLapAngle)
        const newData = [];
        filteredData.forEach(item => {
          newData.push(Object.values(item))
        })
        let mergedArray = newData.reduce((accumulator, subarray) => {
          return accumulator.concat(subarray);
        }, []);
        newData[0].forEach(item1 => {
          let slope1 = calculateSlope(clickPoint[0], clickPoint[1], item1[0], item1[1]);
          newData[1].forEach(item2 => {
            let slope2 = calculateSlope(clickPoint[0], clickPoint[1], item2[0], item2[1]);
            if (slope1 == slope2) {
              console.log(item1, item2);
              mergedArray.forEach((item3, index) => {
                if (item3.join('') == item1.join('') || item3.join('') == item2.join('')) {
                  mergedArray.splice(index, 1);
                }
              })
            }
          })

        })
        newData[0] = mergedArray
        let circleLocation = []
        for (let i = 0; i < filteredData.length; i++) {
          let item = Object.values(filteredData[i])
          for (let j = 0; j < item.length; j++) {
            if (j == 0) {
              let x1 = clickPoint[0]
              let y1 = clickPoint[1]
              let x2 = item[j][0]
              let y2 = item[j][1]
              let x3 = clickPoint[0]
              let y3 = clickPoint[1]
              let x4 = item[j + 1][0]
              let y4 = item[j + 1][1]
              let angleDeg = this.calculateAngleBetweenLines(x1, y1, x2, y2, x3, y3, x4, y4)
            
              this.angleDegs.push(angleDeg)
           
            }
          }
        }
        const temp =this.angleDegs.map((item, index) => {
          if (index == 0) {
            return item -this.angleDegs[1]
          }else {
            return item 
          }
        })
        let outerAngle = 180 - temp.reduce((acc, cur) => acc + cur, 0)
        this.angleDegs.push(outerAngle)
        newData.forEach((item, index) => {
          let x1 = clickPoint[0]
          let y1 = clickPoint[1]
          let x2 = item[0][0]
          let y2 = item[0][1]
          let x3 = clickPoint[0]
          let y3 = clickPoint[1]
          let x4 = item[1][0]
          let y4 = item[1][1]
          // let angleDeg = this.calculateAngleBetweenLines(x1, y1, x2, y2, x3, y3, x4, y4)
          let startAngle = Math.atan2(y2 - y1, x2 - x1);
          let endAngle = Math.atan2(y4 - y1, x4 - x1);
          if (startAngle > endAngle) {
            // 如果是，则交换它们的值  
            let temp = startAngle;
            startAngle = endAngle;
            endAngle = temp;
          }
          const color = getRandomColor(index + 1)
          const radius = 50
          let ctx = canvas.getContext('2d');
          // 画圆弧标注 角度
          ctx.beginPath();
          ctx.arc(x1, y1, radius, startAngle, endAngle);
          ctx.strokeStyle = color;
          ctx.stroke();
          // 写数字
          const radius1 = 150
          const textX = x1 + radius1 * Math.cos((startAngle + endAngle) / 2);
          const textY = y1 + radius1 * Math.sin((startAngle + endAngle) / 2);
          circleLocation.push({
            point: [textX, textY],
            num: index + 1,
            isFilled: false,
            color: color,
          })
          this.model.set("circleLocation", circleLocation)
          // this.angleDegs.push(angleDeg)
          // console.log(angleDeg);
        })
        let outerAnglePoint1 = outerAnglePoint[0]
        let outerAnglePoint2 = Object.values(filteredData[filteredData.length - 1])[0]
        this.drawOuterAngleWithNumber(canvas, outerAnglePoint1, outerAnglePoint2, clickPoint, filteredData.length + 1)
      }

    }
  },
  // 绘制线段和 反向延长线
  drawLineWithExtension(canvas, filteredData, isOvaerLapAngle) {
    let clickPoint = this.model.get("clickPoint")
    let drawing = {
      filteredData,
      clickPoint,
      isOvaerLapAngle,
    }
    this.model.set("drawing", { ...this.model.get("drawing"), ...drawing })
    filteredData.forEach(item => {
      for (const key in item) {
        const element = item[key];
        let slope = calculateSlope(clickPoint[0], clickPoint[1], element[0], element[1]);
        slope = parseFloat(slope.toFixed(1))
        let isExtend = this.compareSlopes(this.slopes, slope)
        let ctx = canvas.getContext('2d');
        // 绘制原始直线
        ctx.beginPath();
        ctx.moveTo(clickPoint[0], clickPoint[1]);
        ctx.lineTo(element[0], element[1]);
        ctx.lineWidth = 4;
        ctx.strokeStyle = 'red';
        ctx.stroke();
        // 绘制反向延长线
        if (isExtend ) {
          // 计算反向延长线的坐标
          let extensionEndX = clickPoint[0] - (element[0] - clickPoint[0]);
          let extensionEndY = clickPoint[1] - (element[1] - clickPoint[1]);
          ctx.beginPath();
          ctx.moveTo(clickPoint[0], clickPoint[1]);
          ctx.lineTo(extensionEndX, extensionEndY);
          ctx.lineWidth = 4;
          ctx.strokeStyle = 'red';
          ctx.stroke();
        }
      }
    })
  },
  // 绘制圆弧标注角度 ，写数字
  drawAngleWithNumber(canvas, filteredData, isOvaerLapAngle) {
    let circleLocation = []
    let clickPoint = this.model.get("clickPoint")
    let drawing = {
      filteredData,
      clickPoint,
      isOvaerLapAngle,
    }
    this.model.set("drawing", { ...this.model.get("drawing"), ...drawing })
    let ctx = canvas.getContext('2d');
    for (let i = 0; i < filteredData.length; i++) {
      let item = Object.values(filteredData[i])
      for (let j = 0; j < item.length; j++) {
        if (j == 0) {
          let x1 = clickPoint[0]
          let y1 = clickPoint[1]
          let x2 = item[j][0]
          let y2 = item[j][1]
          let x3 = clickPoint[0]
          let y3 = clickPoint[1]
          let x4 = item[j + 1][0]
          let y4 = item[j + 1][1]
          let angleDeg = this.calculateAngleBetweenLines(x1, y1, x2, y2, x3, y3, x4, y4)
          let startAngle = Math.atan2(y2 - y1, x2 - x1);
          let endAngle = Math.atan2(y4 - y1, x4 - x1);
          console.log(startAngle, endAngle);
          console.log(startAngle * (180 / Math.PI), endAngle * (180 / Math.PI));
          if (startAngle > endAngle) {
            // 如果是，则交换它们的值  
            let temp = startAngle;
            startAngle = endAngle;
            endAngle = temp;
          }
          const color = getRandomColor(i + 1)
          const radius = 50
          // 画圆弧标注 角度
          ctx.beginPath();
          ctx.arc(x1, y1, radius, startAngle, endAngle);
          ctx.strokeStyle = color;
          ctx.stroke();
          // 写数字
          const radius1 = isOvaerLapAngle ? 200 : 100
          const textX = x1 + radius1 * Math.cos((startAngle + endAngle) / 2);
          const textY = y1 + radius1 * Math.sin((startAngle + endAngle) / 2);
          circleLocation.push({
            point: [textX, textY],
            num: i + 1,
            isFilled: false,
            color: color,
          })
          this.model.set("circleLocation", circleLocation)
          this.angleDegs.push(angleDeg)
        }
      }
    }
    let outerAngle = 180 - this.angleDegs.reduce((acc, cur) => acc + cur, 0)
    this.angleDegs.push(outerAngle)
  },

  //  绘制外角圆弧标注角度，写数字
  drawOuterAngleWithNumber(canvas, outerAnglePoint1, outerAnglePoint2, clickPoint, num) {
    const draw = this.model.get("drawing")
    this.model.set("drawing", { ...draw, outerAngle: { outerAnglePoint1, outerAnglePoint2, clickPoint, num } })
    let circleLocation = this.model.get("circleLocation")
    let ctx = canvas.getContext('2d');
    let startAngle = Math.atan2(outerAnglePoint1[1] - clickPoint[1], outerAnglePoint1[0] - clickPoint[0]);
    let endAngle = Math.atan2(outerAnglePoint2[1] - clickPoint[1], outerAnglePoint2[0] - clickPoint[0]);

    console.log(startAngle, endAngle);
    console.log(startAngle * (180 / Math.PI), endAngle * (180 / Math.PI));
    const color = getRandomColor(num)
    const radius = 50
    ctx.beginPath();
    ctx.arc(clickPoint[0], clickPoint[1], radius, startAngle, endAngle);
    ctx.strokeStyle = color;
    ctx.stroke();
    let textX = 0
    let textY = 0
    console.log(100 * Math.cos((startAngle + endAngle) / 2), 100 * Math.sin((startAngle + endAngle) / 2));
    if (startAngle > endAngle) {
      textX = clickPoint[0] - 100 * Math.cos((startAngle + endAngle) / 2);
      textY = clickPoint[1] - 100 * Math.sin((startAngle + endAngle) / 2);
    } else {
      textX = clickPoint[0] + 100 * Math.cos((startAngle + endAngle) / 2);
      textY = clickPoint[1] + 100 * Math.sin((startAngle + endAngle) / 2);
    }

    circleLocation.push({
      point: [textX, textY],
      num: num,
      isFilled: false,
      color: color,
    })
    this.model.set("circleLocation", circleLocation)


  },
  drawCircle(canvas, textX, textY, color, num, isFilled) {
    let ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.arc(textX, textY, 30, 0, 2 * Math.PI, false);
    ctx.fillStyle = '#63788a';
    if (isFilled) {
      ctx.fill()
    }
    ctx.lineWidth = 2;
    ctx.strokeStyle = color;
    ctx.stroke();
    ctx.font = '30px Arial';
    ctx.fillStyle = color;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText(num, textX, textY);
  },
  findPointAtTriangleIndex(array, targetArray) {
    for (let i = 0; i < array.length; i++) {
      const obj = array[i];
      for (const key in obj) {
        if (JSON.stringify(obj[key]) === JSON.stringify(targetArray)) {
          return i;
        }
      }
    }
    return -1; // 如果未找到匹配项，则返回 -1
  },
  isduplicatePoint(duplicatePoint, point) {
    for (let i = 0; i < duplicatePoint.length; i++) {
      if (point.join('') != duplicatePoint[i][0].join('')) {
        return false
      } else {
        return true
      }
    }
  },
  refreshUI(options) {
    this.open = true;
    let changed = false;
    if (typeof options.preset !== "undefined") {
      this.model.set("preset", options.preset);
      changed = true;
    }
    if (typeof options.isEditMode !== "undefined") {
      this.model.set("isEditMode", options.isEditMode);
      changed = true;
    }
    if (typeof options.recordStrokes !== "undefined") {
      this.model.set("recordStrokes", options.recordStrokes);
      changed = true;
    }
    if (changed) {
      this.model.initData();
      this.render();
      this.setMode(this.model.get("defaultMode"));
    }
  },
});
